package com.kaibes.platform.article.api;

import java.math.BigInteger;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestAttribute;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.kaibes.core.base.builder.SeparatorBuilder;
import com.kaibes.core.base.util.StringUtils;
import com.kaibes.core.spring.bean.BeanUtils;
import com.kaibes.platform.article.db.entity.Article;
import com.kaibes.platform.article.db.service.ArticleService;
import com.kaibes.platform.article.db.service.ArticleTagService;
import com.kaibes.platform.article.pojo.ArticlePost;
import com.kaibes.platform.article.pojo.ArticleUpdate;
import com.kaibes.platform.article.pojo.ArticleUpdateByIds;
import com.kaibes.web.api.ApiLink;
import com.kaibes.web.api.ResponseApi;
import com.kaibes.web.response.ResponseFactory;

@RestController
@RequestMapping("/articles/infos")
public class ArticleApi extends ResponseApi<Article, ArticleService>{

    @Autowired
    private ArticleTagService articleTagService;
    
    @PostMapping
    @ApiLink("创建文章")
    public ResponseEntity<List<BigInteger>> post(@RequestAttribute Integer userId, @RequestBody @Validated ArticlePost data) {
        if (data.getTags() != null) {
            String[] tags = data.getTags().replaceAll("；", ";").split(";");
            List<String> tagList = new ArrayList<>();
            SeparatorBuilder sb = StringUtils.separatorBuilder(";");
            for (String tag : tags) {
                if (tag.isEmpty() || tagList.contains(tag)) {
                    continue;
                }
                sb.appends(tag);
                tagList.add(tag);
            }
            data.setTags(sb.delEnd().toString());
            articleTagService.saveIfNotExist(tagList);
        }
        data.setUserId(userId);
        return super.post(data, "保存文章成功", "保存文章失败");
    }
    
    // ==============================
    @PutMapping("/{id:\\d+}")
    @ApiLink("修改文章，根据id")
    public ResponseEntity<Object> putById(@RequestAttribute Integer userId, @PathVariable BigInteger id, @RequestBody @Validated ArticleUpdate data) {
        if (data.getTags() != null) {
            String[] tags = data.getTags().replaceAll("；", ";").split(";");
            List<String> tagList = new ArrayList<>();
            SeparatorBuilder sb = StringUtils.separatorBuilder(";");
            for (String tag : tags) {
                if (tag.isEmpty() || tagList.contains(tag)) {
                    continue;
                }
                sb.appends(tag);
                tagList.add(tag);
            }
            data.setTags(sb.delEnd().toString());
            articleTagService.saveIfNotExist(tagList);
        }
        Article article = BeanUtils.createTarget(data, Article.class);
        article.setUpdateTime(LocalDateTime.now());
        return super.putById(article, id, "更新文章成功", "更新文章失败");
    }
    
    @PutMapping()
    @ApiLink("修改文章，根据id")
    public ResponseEntity<Object> putByIds(@RequestAttribute Integer userId, @RequestBody @Validated ArticleUpdateByIds update) {
        ArticleUpdate data = update.getData();
        if (data.getTags() != null) {
            String[] tags = data.getTags().replaceAll("；", ";").split(";");
            List<String> tagList = new ArrayList<>();
            SeparatorBuilder sb = StringUtils.separatorBuilder(";");
            for (String tag : tags) {
                if (tag.isEmpty() || tagList.contains(tag)) {
                    continue;
                }
                sb.appends(tag);
                tagList.add(tag);
            }
            data.setTags(sb.delEnd().toString());
            articleTagService.saveIfNotExist(tagList);
        }
        
        Article article = BeanUtils.createTarget(data, Article.class);
        article.setUpdateTime(LocalDateTime.now());
        return super.putByIds(article, update.getIds(), "更新文章成功", "更新文章失败");
    }
    
    
    //=======================
    
    @DeleteMapping
    @ApiLink("删除文章，根据id")
    public ResponseEntity<Object> deleteByIdQuery(@RequestBody List<BigInteger> ids) {
        return super.deleteByIds(ids, "删除文章成功", "删除文章失败");
    }
    
    @DeleteMapping("/{id:\\d+}")
    @ApiLink("删除文章，根据id")
    public ResponseEntity<Object> deleteByIdQuery(@PathVariable BigInteger id) {
        return super.deleteById(id, "删除文章成功", "删除文章失败");
    }
    
  // ============================== self
    @PutMapping("/self/{id:\\d+}")
    @ApiLink("修改自己的文章，根据id")
    public ResponseEntity<Object> putByIdSelf(@RequestAttribute Integer userId, @PathVariable BigInteger id, @RequestBody @Validated ArticleUpdate data) {
        Integer target = service.getUserIdById(id);
        if (!userId.equals(target)) {
            return ResponseFactory.putFailure("不能修改他人的文章！");
        }
        return putById(userId, id, data);
    }
    
    @DeleteMapping("/self")
    @ApiLink("删除自己的文章，根据id")
    public ResponseEntity<Object> deleteByIdQuerySelf(@RequestAttribute Integer userId, @RequestBody List<BigInteger> ids) {
        for (BigInteger id : ids) {
            Integer target = service.getUserIdById(id);
            if (!userId.equals(target)) {
                return ResponseFactory.putFailure("不能删除他人的文章！");
            }
        }
        return deleteByIdQuery(ids);
    }
    
    @DeleteMapping("/self/{id:\\d+}")
    @ApiLink("删除自己的文章，根据id")
    public ResponseEntity<Object> deleteByIdQuerySelf(@RequestAttribute Integer userId, @PathVariable BigInteger id) {
        Integer target = service.getUserIdById(id);
        if (!userId.equals(target)) {
            return ResponseFactory.putFailure("不能删除他人的文章！");
        }
        return deleteByIdQuery(id);
    }
}
